package cn.com.dhcc.turbo.web.controller.monitor;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FileUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import cn.com.dhcc.app.core.base.BaseController;
import cn.com.dhcc.app.core.exception.ServiceException;
import cn.com.dhcc.app.core.handler.modulehandler.WhereCondition;
import cn.com.dhcc.app.core.handler.modulehandler.valuebean.BetweenValue;
import cn.com.dhcc.app.core.handler.pagerhandler.Pager;
import cn.com.dhcc.app.core.handler.pagerhandler.PagerData;
import cn.com.dhcc.app.core.service.Log;
import cn.com.dhcc.app.core.service.Log.LOGTYPE;
import cn.com.dhcc.app.core.util.DTUtil;
import cn.com.dhcc.app.core.util.JsonUtil;
import cn.com.dhcc.app.core.util.StrUtil;
import cn.com.dhcc.app.core.util.UUIDGenerator;
import cn.com.dhcc.app.pub.core.annotation.TurboMenu;
import cn.com.dhcc.app.pub.core.annotation.TurboMenu.LEAF_MENU;
import cn.com.dhcc.app.pub.core.consts.AppConst;
import cn.com.dhcc.app.pub.core.consts.NodeInfoParam;
import cn.com.dhcc.app.pub.core.util.ZipUtil;
import cn.com.dhcc.turbo.entity.exch.CarvedDiscsData;
import cn.com.dhcc.turbo.entity.exch.CarvedDiscsHistory;
import cn.com.dhcc.turbo.entity.exch.CrossNetTmpCmData;
import cn.com.dhcc.turbo.entity.exch.CrossNetTmpFileData;
import cn.com.dhcc.turbo.entity.exch.SendCmData;
import cn.com.dhcc.turbo.entity.exch.SendFileData;
import cn.com.dhcc.turbo.entity.registry.NodeInfo;
import cn.com.dhcc.turbo.entity.sysmgr.UserInfo;
import cn.com.dhcc.turbo.entity.sysmgr.UserInfo.SL_AUTH_FLAG;
import cn.com.dhcc.turbo.service.exch.cmdata.CarvedDiscsDataService;
import cn.com.dhcc.turbo.service.exch.cmdata.CrossNetTmpCmDataService;
import cn.com.dhcc.turbo.service.exch.cmdata.SendCmDataService;
import cn.com.dhcc.turbo.service.exch.filedata.CrossNetTmpFileDataService;
import cn.com.dhcc.turbo.service.exch.filedata.SendFileDataService;
import cn.com.dhcc.turbo.service.registry.BaseInfoService;


/**
 * 刻盘管理Controller
 * 
 * @日期 2014-10-14 下午2:34:28
 * @作者  高强
 */
@Controller
@RequestMapping("/monitor")
@TurboMenu(belongToMenu=LEAF_MENU.CARVED_DISCS_MANAGE)
public class CarvedDiscsManageController extends BaseController {
	@SuppressWarnings("deprecation")
	private static Logger logger = Log.getExistLogger(LOGTYPE.SAI);

	@Autowired
	private CarvedDiscsDataService carvedDiscsDataService;
	
	@Autowired
	private SendCmDataService cmDataService;
	@Autowired
	private SendFileDataService sendFileDataService;
	
	@Autowired
	private CrossNetTmpFileDataService crossNetTmpFileDataService;
	@Autowired
	private CrossNetTmpCmDataService crossNetTmpCmDataService;
	
	@Autowired
	private BaseInfoService baseInfoService;
	
	@RequestMapping(value = "/carved_discs_manage_list")
	public String list(
			Model model, 
			Pager pager, 
			HttpServletRequest request,
			String sendBusicode, 
			String batchId,
			String startCreated, 
			String endCreated, 
			String orderName, 
			String order) {
		try {
			UserInfo userInfo = (UserInfo)BaseController.getCurrentUserInfo(request.getSession());
			boolean isSysUser = userInfo.getSlAuthFlag().equalsIgnoreCase(SL_AUTH_FLAG.SYS_USER.getCode());
			NodeInfo localNode=baseInfoService.getCurrentNodeInfo();
			
			WhereCondition searchData = new WhereCondition();
			searchData.where().notEq("status", AppConst.ProcessStatus.CARVED_DISCS.value());
			
			if (StrUtil.isNotBlank(sendBusicode)) {
				searchData.and().like("send_busicode", sendBusicode);
			}
			
			if (StrUtil.isNotBlank(batchId)) {
				searchData.and().like("batch_id", batchId);
			}
			if (isSysUser) {
				searchData.and().leftBracket()
				.eq("from_table", AppConst.FromTable.SEND_TABLE.value())
				.rightBracket()
				.and().eq("send_adaptorcode", userInfo.getUserName());
			}
			//这里对发生中的状态进行了处理，把本地发送和远程发送都看做为发送中
			/*if (StrUtil.isNotBlank(sendStatus)) {
				if (AppConst.SendStatus.LOCAL_SENDING.value().equals(sendStatus)) {
					searchData.and().leftBracket()
								.eq("send_status", sendStatus)
								.or()
								.eq("send_status", AppConst.SendStatus.REMOTE_SENDING.value())
								.rightBracket();
				} else {
					searchData.and().eq("send_status", sendStatus);
				}
			}*/
			//时间范围从那天到那天
			if (StrUtil.isNotBlank(startCreated) && StrUtil.isNotBlank(endCreated)) {
				searchData.and().between("requestDate", new BetweenValue(DTUtil.toDateTime(startCreated) , DTUtil.toDateTime(endCreated)));
			}

			//时间范围，大于等于某天
			if (StrUtil.isNotBlank(startCreated) && StrUtil.isBlank(endCreated)) {	
				searchData.and().between("requestDate", new BetweenValue(DTUtil.toDateTime(startCreated), null, true, false));
			}

			//时间范围，小于等于某天
			if (StrUtil.isBlank(startCreated) && StrUtil.isNotBlank(endCreated)) {	
				searchData.and().between("requestDate", new BetweenValue(null, DTUtil.toDateTime(endCreated), false, true));
			}
			
			if (StrUtil.isNotBlank(orderName)) {
				searchData.orderBy(orderName + " " + order);
			} else {
				searchData.orderBy("requestDate  desc");
			}
			PagerData<CarvedDiscsData> datas = carvedDiscsDataService.getPagerList(pager, searchData);
			long filesize=carvedDiscsDataService.sumFileSize(searchData);
			List<CarvedDiscsData> dataList = datas.getDatas();
			model.addAttribute(DATA_KEY, dataList);
			model.addAttribute("filesize", filesize);
			model.addAttribute("localNode",localNode);
			model.addAttribute("isInnerCode",NodeInfoParam.isInnerNode());
			setTotoal(model, datas.getTotal());
			return "monitor/carved_discs_manage_list";
		} catch (Exception e) {
			logger.error("操作失败", e);
			return toAlertPage(model, e.getMessage());
		}
	}

	/**
	 * 刻盘
	 * @param model
	 * @param id
	 * @return
	 */
	@SuppressWarnings("static-access")
	@RequestMapping(value = "/carved_discs_manage_carvedDiscs")
	public void carvedDiscs(HttpServletResponse response, String[] id) {
		try {
//			List<List> dataList=new ArrayList<List>();
//			File baseFile=tempFile(id,dataList);//得到要刻盘的pId和对应的sendCmDatas;
//			List<SendCmData> sendCmDatas=null;
//			List<SendFileData> sendFileDatas=null;
//			if (baseFile!=null) {
//				String zipFile= baseFile.getAbsolutePath()+".zip";
//				ZipUtil.compress(baseFile.getAbsolutePath(),zipFile, "gbk", "结构化数据压缩文件");
//				downLoadFile(response, new File(zipFile), new File(zipFile).getName());
//				logger.info("下载完成");
//				
//				CarvedDiscsHistory history=new CarvedDiscsHistory();
//				history.setId(UUIDGenerator.getUUID());
//				history.setCarvedDiscsIds(this.arrayToString(id));
//				history.setCarvedName(new File(zipFile).getName());
//				history.setCarvedSize(new File(zipFile).length());
//				history.setCreated(new Date());
//				//生成刻盘历史记录
//				carvedDiscsDataService.generateHistory(history,dataList);
			
			String[] ids=new String[id.length];//保存id
			String[] filenameIndexs=new String[id.length];//保存文件名索引
		    //解析参数id
			for (int i = 0; i < id.length; i++) {
				String  str = id[i];
				ids[i]=str.split(";")[0];
				filenameIndexs[i]=str.split(";")[1];
			}
			
			File baseFile=tempFile(ids,filenameIndexs);//得到要刻盘的pId和对应的sendCmDatas;
			if (baseFile!=null) {
				String zipFile= baseFile.getAbsolutePath()+".zip";
				ZipUtil.compress(baseFile.getAbsolutePath(),zipFile, "gbk", "结构化数据压缩文件");
				downLoadFile(response, new File(zipFile), new File(zipFile).getName());
				logger.info("下载完成");
				CarvedDiscsHistory history=new CarvedDiscsHistory();
				history.setId(UUIDGenerator.getUUID());
				history.setCarvedDiscsIds(this.arrayToString(ids));
				history.setCarvedName(new File(zipFile).getName());
				history.setCarvedSize(new File(zipFile).length());
				history.setCreated(new Date());
				carvedDiscsDataService.generateHistory(history,ids,filenameIndexs);
			}
		} catch (Exception e) {
			logger.error("操作失败", e);
		}
	}
	


    public File tempFile(String[] id,String[] filenames) throws IOException, ServiceException{
    	NodeInfo localNode=baseInfoService.getCurrentNodeInfo();
    	String dataString=new SimpleDateFormat("yyyyMMDDHHmmss").format(new Date());
    	File baseFile=new File( AppConst.APP_CD_TEMP,"sl_exch_"+localNode.getNodeCode()+"_"+dataString);
		if (!baseFile.exists()) {
			baseFile.mkdirs();
		}
		for (int i = 0; i < id.length; i++) {
			CarvedDiscsData vo= carvedDiscsDataService.get(id[i]);//查询记录
			if (vo==null) {
				return null;
			}
			File file =null;
			if (vo.getPackets()==null || "".equals(vo.getPackets())) {//如果没有进行拆包
				file = new File(AppConst.APP_CD_ZIP,vo.getZipName());
				if (file.exists()) {
					FileUtils.copyFile(file, new File(baseFile,file.getName()));
				}
			}else{//如果进行拆包
				String[] names=vo.getPackets().split(",");
				for (String index : filenames[i].split("_")) {
					file = new File(AppConst.APP_CD_ZIP,names[Integer.parseInt(index)]);
					if (file.exists()) {
						FileUtils.copyFile(file, new File(baseFile,file.getName()));
					}
				}
			}
		}
		return baseFile;
	   
   }
   
	
	@SuppressWarnings({ "rawtypes" })
	public File tempFile(String[] id,List<List> dataList) throws IOException, ServiceException{
		NodeInfo localNode=baseInfoService.getCurrentNodeInfo();
//		String netType=localNode.getNodeCode().substring(6, 7);//获取节点的网络类型，0内网，1外网
		String dataString=new SimpleDateFormat("yyyyMMDDHHmmss").format(new Date());
		File baseFile=new File( AppConst.APP_CD_TEMP,"sl_exch_"+localNode.getNodeCode()+"_"+dataString);
		if (!baseFile.exists()) {
			baseFile.mkdirs();
		}
		for (String string : id) {
			CarvedDiscsData vo;
			vo = carvedDiscsDataService.get(string);
			
			
			String[] strorepaths= vo.getStorepaths().split(",");
			for (String strorepath : strorepaths) {
				String path = vo.getFilehome() + File.separator + strorepath;
				File file = new File(path);
				if (file.exists()) {
					FileUtils.copyFile(file, new File(baseFile,string+File.separator+file.getName()));
				}else {
					baseFile=null;
					break;
				}
			}
			Map<String,Object> map=new HashMap<String, Object>();
			map.put("carvedDiscsData", vo);
            if (vo.getDataType().equals(AppConst.ExchDataType.FILE_DATA.value())) {//
    			WhereCondition parameter = new WhereCondition();
    			if (vo.getFromTable().equals(AppConst.FromTable.SEND_TABLE.value())) {
    				parameter.where().eq("group_id", vo.getBatchId()).and().eq("cross_net", AppConst.CrossNetType.INNER_OUT_NETWORK.value());
        			List<SendFileData> list=sendFileDataService.list(parameter);
        			map.put("data", list);
        			dataList.add(list);
				}else if (vo.getFromTable().equals(AppConst.FromTable.TMP_TABLE.value())) {
					parameter.where().eq("group_id", vo.getBatchId()).and().eq("cross_net", AppConst.CrossNetType.OUT_INNER_NETWORK.value())
					.and().eq("THROUGH_GAP", "2");
        			List<CrossNetTmpFileData> list=crossNetTmpFileDataService.list(parameter);
        			map.put("data", list);
        			dataList.add(list);
				}
			}else{
				WhereCondition parameter = new WhereCondition();
    			if (vo.getFromTable().equals(AppConst.FromTable.SEND_TABLE.value())) {
        			parameter.where().eq("pid", vo.getBatchId()).and().eq("cross_net", AppConst.CrossNetType.INNER_OUT_NETWORK.value());
        			List<SendCmData> list=cmDataService.list(parameter);
        			map.put("data", list);
        			dataList.add(list);
				}else if (vo.getFromTable().equals(AppConst.FromTable.TMP_TABLE.value())) {
					parameter.where().eq("pid", vo.getBatchId()).and().eq("cross_net", AppConst.CrossNetType.OUT_INNER_NETWORK.value())
					.and().eq("THROUGH_GAP", "2");
        			List<CrossNetTmpCmData> list=crossNetTmpCmDataService.list(parameter);
        			map.put("data", list);
        			dataList.add(list);
				}
			}
			JsonUtil.toJsonFile(new File(baseFile,string+File.separator+string+".json"), map);
		}
		return baseFile;
	}
	/** 
	 * @Description:把list转换为一个用逗号分隔的字符串 
	 */  
	public static String arrayToString(Object[] arr) {  
	    StringBuilder sb = new StringBuilder();  
	    if (arr != null && arr.length > 0) {  
	        for (int i = 0; i < arr.length; i++) {  
	            if (i < arr.length- 1) {  
	                sb.append(arr[i] + ",");  
	            } else {  
	                sb.append(arr[i]);  
	            }  
	        }  
	    }  
	    return sb.toString();  
	}  
	
}
